using System.Collections.Generic;
using System.Linq;
using Amba.OrchardTools.Drivers;
using Amba.System.Extensions;
using Amba.ULogin.ViewModels;
using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Localization;
using Orchard.Roles.Services;
using Orchard.UI.Notify;
using Amba.ULogin.Models;

namespace Amba.ULogin.Drivers
{
    [UsedImplicitly]
	
    public class ULoginPartDriver : DriverBase<ULoginPart>
    {
        private readonly INotifier _notifier;
        private const string TemplateName = "Parts/ULoginPart";
        private readonly IRoleService _roleService;

        public Localizer T { get; set; }

        public ULoginPartDriver(INotifier notifier, IRoleService roleService)
        {
            _notifier = notifier;
            _roleService = roleService;
            T = NullLocalizer.Instance;
        }				
		
        protected override DriverResult Display(ULoginPart part, string displayType, dynamic shapeHelper)
        {
            return ContentShape("Parts_ULoginPart",
                () => shapeHelper.Parts_ULoginPart(ContentItem: part.ContentItem));
        }

        protected override DriverResult Editor(ULoginPart part, dynamic shapeHelper)
        {
            var viewModel = new ULoginPartEditorViewModel();
            viewModel.AllRoles = _roleService.GetRoles().Select(x => x.Name).ToList();
            if (!string.IsNullOrEmpty(part.RolesForCreatedUsers))
            {
                viewModel.SelectedRoles = part.RolesForCreatedUsers.FromJson<List<string>>();
            }
            else
            {
                viewModel.SelectedRoles = new List<string>();
            }
            return ContentShape("Parts_ULoginPart",
                    () => shapeHelper.EditorTemplate(
                        TemplateName: TemplateName, 
                        Model: viewModel, 
                        Prefix: Prefix));
        }

        protected override DriverResult Editor(ULoginPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            var viewModel = new ULoginPartEditorViewModel();
            if (updater.TryUpdateModel(viewModel, Prefix, null, null))
            {
                part.RolesForCreatedUsers = viewModel.SelectedRoles.ToJson();

                _notifier.Information(T("ULoginPart edited successfully"));
            }
            else
            {
                _notifier.Error(T("Error during ULoginPart update!"));
            }
            return Editor(part, shapeHelper);
        }

    }
}